package com.cheli.managerAsset.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cheli.commonutils.R;
import com.cheli.managerAsset.entity.AsAsset;
import com.cheli.managerAsset.entity.vo.AssetDepVo;
import com.cheli.managerAsset.entity.vo.AssetInfoVo;
import com.cheli.managerAsset.entity.vo.AssetPublishVo;
import com.cheli.managerAsset.entity.vo.AssetQuery;
import com.cheli.managerAsset.service.AsAssetDescriptionService;
import com.cheli.managerAsset.service.AsAssetService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 资产 前端控制器
 * </p>
 *
 * @author cheli
 * @since 2021-03-28
 */
@RestController
@RequestMapping("/asManager/asset")
@Api(value = "category", tags = "资产管理")
@CrossOrigin
@Slf4j
public class AsAssetController {
    @Autowired
    private AsAssetService asAssetService;

    @Autowired
    private AsAssetDescriptionService asAssetDescriptionService;

   @PostMapping("addAssetInfo")
    public R addAssetInfo(@RequestBody AssetInfoVo assetInfoVo){
       String id = asAssetService.addAssetInfo(assetInfoVo);
        log.info("增加资产"+id);
        return R.ok().data("assetId",id);
    }

    @ApiOperation("逻辑删除资产")
    @DeleteMapping("{id}")
    public R removeById(@PathVariable String id) {
        log.info("删除资产"+ id);
        boolean flag = asAssetService.removeById(id);
        asAssetDescriptionService.removeById(id);
        if (flag) {
            return R.ok();
        } else {
            return R.error();
        }
    }

    @GetMapping("getAssetInfo/{id}")
    public R getAssetInfo(@PathVariable String id){
        AssetInfoVo assetInfoVo = asAssetService.getAssetInfo(id);
        log.info("查询资产"+id);
        return R.ok().data("assetInfoVo",assetInfoVo);
    }

   @GetMapping("getPublishAssetInfoByAssetId/{id}")
    public R getPublishAssetInfo(@PathVariable String id){
        AssetPublishVo assetInfoVo = asAssetService.getPublishAssetInfoByAssetId(id);
        log.info("查询发布前资产"+id);
        return R.ok().data("publishAsset",assetInfoVo);
    }

    @GetMapping("publishAsset/{id}")
    public R publishAsset(@PathVariable String id){
        AssetInfoVo asAsset = new AssetInfoVo();
        asAsset.setId(id);
        asAsset.setStatus("Normal");
        asAssetService.updateAssetById(asAsset);
        log.info("发布资产"+id);
        return R.ok();
    }

    @PostMapping("updateAssetInfo")
    public R updateAssetInfo(@RequestBody AssetInfoVo assetInfoVo){
        asAssetService.updateAssetById(assetInfoVo);
        log.info("发布资产"+assetInfoVo.getId());
        return R.ok();
    }

    @PostMapping("pageAssetCondition/{current}/{limit}")
    public R pageAssetCondition(@PathVariable Long current,
                                    @PathVariable Long limit,
                                    @RequestBody(required = false) AssetQuery assetQuery){
        log.info("资产分页条件查询" + assetQuery.toString());
       Page<AsAsset> page = new Page<>(current, limit);
        QueryWrapper<AsAsset> queryWrapper = new QueryWrapper<>();

        String begin = assetQuery.getBegin();
        String categoryId = assetQuery.getCategoryId();
        String categoryParentId = assetQuery.getCategoryParentId();
        String end = assetQuery.getEnd();
        String title = assetQuery.getTitle();
        String id = assetQuery.getId();
        String status = assetQuery.getStatus();

        if (!StringUtils.isEmpty(id)) {
            queryWrapper.eq("id", id);
        }
        if (!StringUtils.isEmpty(status)) {
            queryWrapper.eq("status", status);
        }
        if (!StringUtils.isEmpty(title)) {
            queryWrapper.like("title", title);
        }
        if (!StringUtils.isEmpty(categoryId)) {
            queryWrapper.eq("category_id", categoryId);
        }
        if (!StringUtils.isEmpty(categoryParentId)) {
            queryWrapper.eq("category_parent_id", categoryParentId);
        }
        if (!StringUtils.isEmpty(begin)) {
            queryWrapper.ge("gmt_create", begin);
        }

        if (!StringUtils.isEmpty(end)) {
            queryWrapper.le("gmt_create", end);
        }

        queryWrapper.orderByAsc("sort");

        asAssetService.page(page, queryWrapper);

        long total = page.getTotal();
        List<AsAsset> records = page.getRecords();
        return R.ok().data("total", total).data("rows", records);
    }

    @PostMapping("pageDepAssetCondition/{current}/{limit}")
    public R pageDepAssetCondition(@PathVariable Long current,
                                  @PathVariable Long limit,
                                  @RequestBody(required = false) AssetQuery assetQuery){
        log.info("资产折旧分页条件查询" + assetQuery.toString());
       Page<AsAsset> page = new Page<>(current, limit);
        QueryWrapper<AsAsset> queryWrapper = new QueryWrapper<>();

        String begin = assetQuery.getBegin();
        String end = assetQuery.getEnd();
        String method = assetQuery.getMethod();
        String title = assetQuery.getTitle();
        String id = assetQuery.getId();

        if (!StringUtils.isEmpty(id)) {
            queryWrapper.eq("id", id);
        }
        if (!StringUtils.isEmpty(title)) {
            queryWrapper.like("title", title);
        }
        if (!StringUtils.isEmpty(method)) {
            queryWrapper.eq("method", method);
        }
        if (!StringUtils.isEmpty(begin)) {
            queryWrapper.ge("gmt_create", begin);
        }
        if (!StringUtils.isEmpty(end)) {
            queryWrapper.le("gmt_create", end);
        }

        queryWrapper.orderByAsc("sort");

        asAssetService.page(page, queryWrapper);

        long total = page.getTotal();
        List<AsAsset> records = page.getRecords();
        List<AssetDepVo> depRecords = new ArrayList<>();
        AssetDepVo assetDepVo = null;

       for(AsAsset asAsset : records){
            assetDepVo = new AssetDepVo();
            BigDecimal price = asAsset.getPrice();
            BeanUtils.copyProperties(asAsset, assetDepVo);

            Date addDate = asAsset.getGmtCreate();
            LocalDate addLocal = addDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
            LocalDate nowLocal = LocalDate.now();
            LocalDate endLocal = addLocal.plusYears(asAsset.getYear());
           assetDepVo.setExEndTime(endLocal.toString());
            if(nowLocal.isAfter(endLocal)){
                assetDepVo.setEndTime(endLocal.toString());
            }

           int year = nowLocal.getYear() - addLocal.getYear();
            int month = nowLocal.getMonthValue() - addLocal.getMonthValue();
            int useMonth = year * 12 + month;
            assetDepVo.setMonth(String.valueOf(useMonth));



            BigDecimal dep = null;
            BigDecimal dep2 = null;
           if (asAsset.getMethod() == 1) {
                dep = BigDecimal.valueOf(100 - asAsset.getNetSalvage()).divide(new BigDecimal(100),5,BigDecimal.ROUND_HALF_UP).divide(new BigDecimal(asAsset.getYear()),5,BigDecimal.ROUND_HALF_UP);
                dep = dep.divide(new BigDecimal(12),10000,BigDecimal.ROUND_HALF_UP);
               assetDepVo.setDepPrice(String.valueOf(price.multiply(dep).setScale(2,   BigDecimal.ROUND_HALF_UP).doubleValue()));
               assetDepVo.setLastPrice(price
                        .subtract(new BigDecimal(assetDepVo.getDepPrice()).multiply(BigDecimal.valueOf(useMonth)))
                        .setScale(2,   BigDecimal.ROUND_HALF_UP).toString());

               List<String> priceList = new ArrayList<>();
                priceList.add(price.setScale(2,   BigDecimal.ROUND_HALF_UP).toString());
                for (int i =0; i < asAsset.getYear() * 12; i++){
                    price = price.subtract(new BigDecimal(assetDepVo.getDepPrice()));
                    priceList.add(price.setScale(2,   BigDecimal.ROUND_HALF_UP).toString());
                }
                assetDepVo.setExLastPrice(price.setScale(2,   BigDecimal.ROUND_HALF_UP).toString());
                assetDepVo.setPriceList(priceList);
                System.out.println(priceList);

            } else {
                dep = BigDecimal.valueOf(100 - asAsset.getNetSalvage()).divide(new BigDecimal(100),5,BigDecimal.ROUND_HALF_UP).divide(new BigDecimal(asAsset.getYear()),5,BigDecimal.ROUND_HALF_UP);
                dep2 = BigDecimal.valueOf(2.0 / asAsset.getYear());
                dep = dep.divide(new BigDecimal(12),10000,BigDecimal.ROUND_HALF_UP);
                dep2 = dep2.divide(new BigDecimal(12),10000,BigDecimal.ROUND_HALF_UP);


                if(asAsset.getYear() > 2 && asAsset.getYear() - year >=2){
                    for(int i = 0; i < useMonth / 12; i++){
                        price = price.subtract(price.multiply(dep2).multiply(BigDecimal.valueOf(12)));
                    }
                   assetDepVo.setDepPrice(String.valueOf(price.multiply(dep2).setScale(2,   BigDecimal.ROUND_HALF_UP).doubleValue()));
                   assetDepVo.setLastPrice(price.subtract(price.multiply(dep2).multiply(BigDecimal.valueOf(useMonth % 12)))
                            .setScale(2,   BigDecimal.ROUND_HALF_UP).toString());
                }else{
                    for(int i = 0; i < Math.max(asAsset.getYear() - 2, 0); i++){
                        price = price.subtract(price.multiply(dep2).multiply(BigDecimal.valueOf(12)));
                    }
                   assetDepVo.setDepPrice(String.valueOf(price.multiply(dep).setScale(2,   BigDecimal.ROUND_HALF_UP).doubleValue()));
                   assetDepVo.setLastPrice(price
                            .subtract(price.multiply(dep).multiply(BigDecimal.valueOf(useMonth - 12 * Math.max(asAsset.getYear() - 2, 0))))
                            .setScale(2,   BigDecimal.ROUND_HALF_UP).toString());
                }
               price = asAsset.getPrice();
                List<String> priceList = new ArrayList<>();
                priceList.add(price.setScale(2,   BigDecimal.ROUND_HALF_UP).toString());
                double doublePrice = price.doubleValue();
                for(int i = 0; i < Math.max(asAsset.getYear() - 2, 0) * 12; i++){
                    doublePrice = doublePrice - (doublePrice * dep2.doubleValue());
                    price = new BigDecimal(doublePrice);
                    priceList.add(price.setScale(2,   BigDecimal.ROUND_HALF_UP).toString());
                }
                BigDecimal depPrice = price.multiply(dep);
                for (int i =0; i < Math.min(asAsset.getYear() * 12, 24) ; i++){
                    price = price.subtract(depPrice);
                    priceList.add(price.setScale(2,   BigDecimal.ROUND_HALF_UP).toString());
                }

                assetDepVo.setExLastPrice(price.setScale(2,   BigDecimal.ROUND_HALF_UP).toString());
                assetDepVo.setPriceList(priceList);
                System.out.println(priceList);
            }

            depRecords.add(assetDepVo);
        }
        return R.ok().data("total", total).data("rows", depRecords);
    }

    @ApiOperation("更新资产状态")
    @GetMapping("updateStatus/{id}/{status}")
    public R updateStatus(@PathVariable String id,
                          @PathVariable String status){
        AsAsset asset = asAssetService.getById(id);
        asset.setStatus(status);
        asAssetService.updateById(asset);
        return R.ok();
    }

}

